<template>
  <basic-modal v-bind="$attrs" @confirm="handleSubmit">
    <n-form ref="formRef" :model="modelForm" :rules="rules">
      <n-form-item label="类别名称" path="name">
        <n-input placeholder="请输入类别名称" v-model:value="modelForm.name" />
      </n-form-item>
      <n-form-item label="状态" path="status">
        <n-select
          v-model:value="modelForm.status"
          :options="CATEGORY_STATUS"
          placeholder="请选择状态"
        />
      </n-form-item>
      <n-form-item label="排序" path="sort">
        <n-input-number
          class="w-full"
          clearable
          placeholder="请输入排序"
          v-model:value="modelForm.sort"
        />
      </n-form-item>
      <n-form-item label="图标" path="icon">
        <n-upload
          response-type="json"
          :max="1"
          :headers="headers"
          :action="`${uploadUrl}?biz=categories`"
          v-model:file-list="fileList"
          list-type="image-card"
          @finish="handleUploadFinish"
          @remove="handleUploadRemove"
        >
          点击上传
        </n-upload>
      </n-form-item>
      <n-form-item label="描述" path="slug">
        <n-input
          placeholder="请输入描述"
          type="textarea"
          v-model:value="modelForm.slug"
        />
      </n-form-item>
    </n-form>
  </basic-modal>
</template>
<script setup lang="ts">
import { v4 as uuidv4 } from "uuid";
import { reactive, ref, watch } from "vue";
import { debounce } from "lodash-es";
import { FormInst, UploadFileInfo, useMessage } from "naive-ui";
import BasicModal from "@/components/normal/basicModal/index.vue";
import { DictStorage } from "@/storage/dict.storage";
import { getHeaders } from "@/common/utils/comps/index";
import { uploadUrl } from "@/api/basic/basic.api";
import { createCategory, editCategory } from "@/api/product/category.api";
import { ICategoryModalProps } from "./props";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { get, isEmpty } from "lodash-es";
import { Category } from "@/types/model/product/vos/category.vo";
import { useAttrs } from "vue";

const rules = {
  name: [
    {
      required: true,
      message: "请输入产品分类名称",
      trigger: "change",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择状态",
      trigger: "change",
    },
  ],
};

const CATEGORY_STATUS = DictStorage.getDictItemsByCode("pos_category_status");

const emits = defineEmits(["createSuccess", "editSuccess"]);

const props = withDefaults(defineProps<ICategoryModalProps>(), {
  actionType: ActionTypeEnum.ADD,
});

const $attrs = useAttrs();
const message = useMessage();
const headers = getHeaders();

const fileList = ref<UploadFileInfo[]>([]);
const formRef = ref<FormInst | null>(null);
const modelForm = reactive<Category>({
  name: "",
  status: undefined,
  sort: 0,
  slug: "",
  icon: "",
});

watch(
  () => $attrs.show,
  (newVal) => {
    console.log(`newVal:${newVal}`);
    if (!newVal) {
      modelForm.name = "";
      modelForm.status = undefined;
      modelForm.sort = 0;
      modelForm.slug = "";
      modelForm.icon = "";
      fileList.value = [];
    }
  }
);

watch(
  () => [props.actionType, props.formData],
  ([newActionType, newFormData]) => {
    if (newActionType === ActionTypeEnum.EDIT && !isEmpty(newFormData)) {
      const { name, status, sort, icon, slug, id } = newFormData as Category;
      modelForm.name = name;
      modelForm.status = status;
      modelForm.sort = sort;
      modelForm.icon = icon;
      modelForm.slug = slug;
      modelForm.id = id;
      if (icon) {
        fileList.value.push({
          id: uuidv4(),
          name: "icon",
          status: "finished",
          url: icon,
        });
      }
    }
  }
);

const handleSubmit = debounce(function () {
  console.log(fileList);
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }

    if (ActionTypeEnum.ADD === props.actionType) {
      createCategory({
        name: modelForm.name,
        status: modelForm.status,
        sort: modelForm.sort,
        slug: modelForm.slug,
        icon: modelForm.icon,
      }).then(() => {
        message.success("添加成功");
        modelForm.name = "";
        formRef.value?.restoreValidation();
        emits("createSuccess");
      });
    } else {
      editCategory({
        id: modelForm.id,
        name: modelForm.name,
        status: modelForm.status,
        sort: modelForm.sort,
        slug: modelForm.slug,
        icon: modelForm.icon,
      }).then(() => {
        message.success("修改成功");
        modelForm.name = "";
        formRef.value?.restoreValidation();
        emits("editSuccess");
      });
    }
  });
}, 200);

const handleUploadFinish = (payload: any) => {
  console.log(payload);
  const url = get(payload, "event.target.response.message") || "";
  if (url) {
    modelForm.icon = url;
  }
};

const handleUploadRemove = (payload: any) => {
  console.log(payload);
  modelForm.icon = "";
};
</script>
